﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WCITZ.Controllers
{
    public class RollController : Controller
    {
        public ActionResult Index()
        {
			var db = new WCITZEntities();

			foreach (var table in db.Tables.ToList())
			{
				if (table.Name == Request.Form["tableName"])
				{
					foreach (var player in table.Players.ToList())
					{
						if (player.Name == Request.Form["playerName"])
						{
							player.Status = 2;

							db.Players.Attach(player);
							db.Entry(player).State = System.Data.EntityState.Modified;
							db.SaveChanges();
						}
					}
				}
			}

			bool found = false;
			foreach (var table in db.Tables.ToList())
			{
				if (table.Name == Request.Form["tableName"])
				{
					foreach (var player in table.Players.ToList())
					{
						if (player.Status != 2)
						{
							found = true;
							break;
						}
					}
				}
			}

			if (!found)
			{
				/*
				 * Calculate results & Change statuses
				 */
				var count = 0;
				List<int> lst = new List<int>();
				foreach (var table in db.Tables.ToList())
				{
					if (table.Name == Request.Form["tableName"])
					{
						count = table.Players.Count;

						for(var i=0; i<count; i++)
						{
							lst.Add(i);
						}

						Shuffle(lst);

						var j = 0;
						foreach (var player in table.Players.ToList())
						{
							player.Result = lst[j];
							player.Status = 1;

							db.Players.Attach(player);
							db.Entry(player).State = System.Data.EntityState.Modified;
							db.SaveChanges();

							j++;
						}
						break;
					}
					
				}
				/**/
			}
			
			return View();
        }

		public static void Shuffle(List<int> list)
		{
			Random rng = new Random();
			int n = list.Count;
			while (n > 1)
			{
				n--;
				int k = rng.Next(n + 1);
				int value = list[k];
				list[k] = list[n];
				list[n] = value;
			}
		}
    }
}
